﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AMing.Extension.Net40;

namespace Html5Music.Method
{/// <summary>
    /// 管理员权限验证
    /// </summary>
    public class AdminAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 权限
        /// </summary>
        public UserAccess Access { get; set; }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            BaseController adminbase = filterContext.Controller as BaseController;
            if (adminbase != null)
            {
                bool isRedirect = false;
                string redirectUrl = "/admin/login.html";

                if (this.Access != UserAccess.None)
                {
                    string this_access = string.Format(",{0}", this.Access);
                    string username = string.Format("userid:{0}", filterContext.HttpContext.User.Identity.Name);

                    if (adminbase.Admin_Access == null ||
                        !(adminbase.Admin_Access.Contains(this_access) &&
                          adminbase.Admin_Access.Contains(username)))
                    {
                        isRedirect = true;
                        redirectUrl = "/admin/index.html";
                    }
                }
                else
                {
                    isRedirect = true;
                    string rawUrl = filterContext.HttpContext.Request.RawUrl;
                    if (!string.IsNullOrWhiteSpace(rawUrl))
                    {
                        redirectUrl = "{0}?returnUrl={1}".ToFromat(redirectUrl, HttpUtility.UrlEncode(rawUrl));
                    }
                }
                if (isRedirect)
                {
                    filterContext.HttpContext.Response.Redirect(redirectUrl);
                }
            }

            base.OnAuthorization(filterContext);
        }
    }
}